package com.jhh.pay.center.cfg;

import com.jhh.pay.center.dao.TableMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author tangxd
 * @Description: 自动建表策略(现阶段只创建orders表,按季度分表,每次重启自动创建两年内的季度表)
 * @date 2017/12/15
 */
@Component
public class InitTableSplictAware implements ApplicationContextAware {

    @Autowired
    private TableMapper tableMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.initOrderTable();
    }

    private void initOrderTable() {
        List<String> tables = tableMapper.selectOrderTables();

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY");
        Date date = new Date();

        for (int addYears = 0; addYears < 2; addYears++) {
            calendar.setTime(date);
            calendar.add(Calendar.YEAR, addYears);
            date = calendar.getTime();
            for (int i = 1; i <= 4; i++) {
                StringBuilder sb = new StringBuilder("orders");
                sb.append("_");
                sb.append(sdf.format(date));
                sb.append("_");
                sb.append(i);
                if (!existTbl(tables, sb.toString())) {
                    tableMapper.createOrderTable(sb.toString());
                }
            }
        }
    }

    private boolean existTbl(List<String> tbls, String tblName) {
        for (String name : tbls) {
            if (name.equals(tblName)) {
                return true;
            }
        }
        return false;
    }
}
